import 'dart:convert';
import 'dart:io';
import 'dart:math';

class UdpSender {
  RawDatagramSocket? socketV4;
  RawDatagramSocket? socketV6;
  int localPort;
  int ttl;

  UdpSender({int? usePort, this.ttl = 1})
      : localPort = usePort ?? (10000 + Random().nextInt(1000));

  Future<int> send(List<int> buffer, InternetAddress address, int port) async {
    if (address.type == InternetAddressType.IPv4) {
      socketV4 ??=
          await RawDatagramSocket.bind(InternetAddress.anyIPv4, localPort);
      return socketV4!.send(buffer, address, port);
    }

    if (address.type == InternetAddressType.IPv6) {
      socketV6 ??=
          await RawDatagramSocket.bind(InternetAddress.anyIPv6, localPort);
      return socketV6!.send(buffer, address, port);
    }
    return 0;
  }

  void close() {
    if (socketV4 != null) {
      socketV4!.close();
    }
    if (socketV6 != null) {
      socketV6!.close();
    }
  }

  Future<int> sendString(String data, InternetAddress address, int port,
          {Encoding encode = utf8}) =>
      send(encode.encode(data), address, port);
}

